// pages/sessions/sessions-main/sessions-main.ts
import { WeilaCore, WL_ServiceAttribute, WL_ServiceSession, WL_SessionInfo, WL_MsgDataType } from "weilasdk_lite";
import * as Long from "long";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 'message',
    messages: [] as any,
    loading: false,
    isRefreshing: false, // Flag to indicate if the page is refreshing
    loadingText: '' // Text to display in the loading mask
  },

  onPullRefresh() {
    console.log("onPullRefresh");
    this.setData({
      isRefreshing: true // Set a flag to indicate that the page is refreshing
    });
    this.loadSessionList().then(() => {
      console.log('Page refreshed successfully');
    }).catch((err) => {
      console.error('Error refreshing page:', err);
      wx.showToast({
        title: '刷新失败',
        icon: 'none',
        duration: 2000
      });
    }).finally(() => {
      this.setData({
        isRefreshing: false // Reset the refreshing flag
      });
    });
  },


  getMessageLabel(msgData: any): string {
    if (!msgData) return '';
    
    switch (msgData.msgType) {
      case WL_MsgDataType.WL_MSG_DATA_TEXT_TYPE:
        return msgData.textContent || '';
      case WL_MsgDataType.WL_MSG_DATA_AUDIO_TYPE:
        return '[语音]';
      case WL_MsgDataType.WL_MSG_DATA_IMAGE_TYPE:
        return '[图片]';
      case WL_MsgDataType.WL_MSG_DATA_VIDEO_TYPE:
        return '[视频]';
      case WL_MsgDataType.WL_MSG_DATA_FILE_TYPE:
        return '[文件]';
      case WL_MsgDataType.WL_MSG_DATA_LOCATION_TYPE:
        return '[位置]';
      case WL_MsgDataType.WL_MSG_DATA_COMMAND_TYPE:
        return '[命令]';
      case WL_MsgDataType.WL_MSG_DATA_PTT_TYPE:
        return '[对讲]';
      case WL_MsgDataType.WL_MSG_DATA_SERVICE_TYPE:
        return '[服务]';
      case WL_MsgDataType.WL_MSG_DATA_SWITCH_TYPE:
        return '[切换]';
      case WL_MsgDataType.WL_MSG_DATA_WITHDRAW_TYPE:
        return '[撤回]';
      default:
        return '[未知消息]';
    }
  },

  // show loading mask with async/await
  async showLoading(text: string): Promise<void> {
    return new Promise((resolve) => {
      this.setData(
        {
          loading: true,
          loadingText: text,
        },
        () => {
          resolve(); // Resolve the promise when setData callback is triggered
        }
      );
    });
  },
  // hide loading mask with async/await
  async hideLoading(): Promise<void> {
    return new Promise((resolve) => {
      this.setData(
        {
          loading: false,
          loadingText: '',
        },
        () => {
          resolve(); // Resolve the promise when setData callback is triggered
        }
      );
    });
  },


  async loadSessionList() {
    try {
      await this.showLoading('加载中...'); // Show loading mask with text
      let weilaCore: WeilaCore = getApp<IAppOption>().globalData.weilaCore!;
      let getSessionRsp = await weilaCore.weila_get_session_info(Math.floor(Date.now() / 1000));
      let sessions = weilaCore.weila_get_session_info_from_raw_session_data(getSessionRsp.sessionInfoList!);
      console.log("weila_get_session_info", sessions);

      let sessionIds = sessions.map((session: WL_SessionInfo) => {
        return session.sessionId!;
      });

      let getServiceSessionRsp = await weilaCore.weila_business_get_sessions(sessionIds);
      let serviceSessions = getServiceSessionRsp.sessions;
      console.log("weila_business_get_sessions", serviceSessions);

      let sessionsMap = new Map<string, WL_SessionInfo>();
      sessions.forEach((session: WL_SessionInfo) => {
        sessionsMap.set(session.sessionId!.toString(), session);
      });

      let messages = serviceSessions.map((serviceSession: WL_ServiceSession) => {
        let serviceAttribute: WL_ServiceAttribute = serviceSession.serviceAttribute!;
        let msg = {
          avatar: serviceAttribute.avatar!,
          name: serviceAttribute.name!,
          sessionId: '',
          lastMessage: '',
          lastMsgId: 0,
          time: '',
          unread: 0
        } as any;

        let sessionId = new Long(serviceSession.customerAttribute!.userInfo!.userId!, serviceSession.serviceAttribute!.id!);
        let sessionInfo = sessionsMap.get(sessionId.toString());
        if (sessionInfo) {
          let latesMsgDatas = weilaCore.weila_get_msg_data_from_raw_msg_data([sessionInfo.latestMsgData!]);
          msg.lastMessage = this.getMessageLabel(latesMsgDatas[0]);
          msg.lastMsgId = sessionInfo.latestMsgData ? sessionInfo.latestMsgData!.msgId! : 0;
          msg.time = new Date(sessionInfo.latestMsgData!.created!.toNumber() * 1000).toLocaleString();
          msg.unread = sessionInfo.readMsgId! - sessionInfo.latestMsgData!.msgId!;
          msg.sessionId = sessionId.toString();
        }

        return msg;
      });

      this.setData({
        messages: messages
      });
      console.log("Session list loaded", messages);
    }catch (error) {
      console.error("Error loading session list", error);
      this.setData({
        messages: []
      });
    } finally {
      await this.hideLoading(); // Hide loading mask
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.setNavigationBarTitle({
      title: "消息"
    });

    // Page initialization
    this.loadSessionList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // First render complete
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1  // Set to the appropriate tab index (0-3)
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onSessionClick (e: any) {
    console.log("onSessionClick", e)
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: 'pages/sessions/session-chat/session-chat?sessionId=' + item.sessionId + '&lastMsgId=' + item.lastMsgId
    });
  }
})